package org.nerve.fs;

import org.nerve.fs.common.FilenameUtils;

import java.io.InputStream;
import java.io.Serializable;

/**
 * 分布式文件对象
 * org.nerve.fs
 * Created by zengxm on 2015/9/28 0028.
 */
public class DFile implements Serializable, Comparable<DFile>{

	/**
	 * 统一的文件路径分隔符
	 */
	public static final String separator = "/";

	protected String name;            //文件名
	protected long length;            //文件长度
	protected String parent;          //所属文件夹

	protected boolean file;             //是否为文件，只有两中可能，文件或者目录
	protected boolean exist;            //指定的文件是否存在

	protected InputStream inputStream;

	public static DFile build(final String fullFilePath){
		DFile f = new DFile();
		String path = FilenameUtils.toDFSPath(fullFilePath);
		f.name = FilenameUtils.getName(path);
		f.parent = FilenameUtils.getFullPathNoEndSeparator(path);

		return f;
	}

	/**
	 * 不存在的DFS文件
	 * @return
	 */
	public static final DFile noExist(){
		DFile f = new DFile();
		f.exist = false;
		return f;
	}

	public DFile(){
	}

	public DFile(boolean isDirectory, String parent, String name, long length, InputStream is){
		this.exist = true;
		this.file = !isDirectory;
		this.parent = parent;
		this.name = name;
		this.length = length;
		this.inputStream = is;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public long length(){
		return length;
	}

	/**
	 * 是否为一级目录
	 * @return
	 */
	public boolean isRoot(){
		return separator.equals(parent);
	}

	/**
	 * 判断是否为文件
	 * @return
	 */
	public boolean isFile(){
		return file;
	}

	/**
	 * 判断是否为文件夹
	 * @return
	 */
	public boolean isDirectory(){
		return !file;
	}

	public boolean exist(){
		return exist;
	}

	/**
	 * 获取文件的完整路径
	 * @return
	 */
	public String getAbsolutePath(){
		if(separator.equals(parent))
			return parent+name;
		return parent+ separator + name;
	}

	public String getParent(){
		return parent;
	}

	public String getName(){
		return name;
	}

	@Override
	public int compareTo(DFile o) {
		if(o == null)
			return -1;
		return this.getAbsolutePath().compareTo(o.getAbsolutePath());
	}
}
